<!DOCTYPE html>
{% load static %}
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>录入密码 - 实验室门禁系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #4a6cf7;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
            --border-radius: 8px;
            --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: #f5f7fb;
            color: #333;
            line-height: 1.6;
            padding: 0;
            margin: 0;
        }
        
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(180deg, var(--primary-color) 10%, #224abe 100%);
            color: white;
            position: fixed;
            width: 250px;
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 1rem;
            transition: all 0.2s;
        }
        
        .sidebar .nav-link:hover {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar .nav-link.active {
            color: white;
            font-weight: bold;
        }
        
        .sidebar .sidebar-brand {
            height: 4.375rem;
            text-decoration: none;
            font-size: 1.2rem;
            font-weight: 800;
            padding: 1.5rem 1rem;
            text-align: center;
            letter-spacing: 0.05rem;
            color: white;
        }
        
        .main-content {
            margin-left: 250px;
            padding: 1.5rem;
        }
        
        .user-info {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 1rem;
        }
        
        .user-info .user-name {
            font-weight: bold;
            font-size: 1.1rem;
        }
        
        .container {
            max-width: 800px;
            margin: 40px auto;
            padding: 20px;
        }
        
        .card {
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 30px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            animation: cardSlideIn 0.5s ease-out;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 24px;
            color: var(--dark-color);
        }
        
        .back-button {
            background: var(--light-color);
            color: var(--dark-color);
            border: none;
            padding: 8px 15px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .back-button:hover {
            background: #e2e6ea;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark-color);
        }
        
        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 16px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }
        
        input[type="text"]:focus,
        input[type="password"]:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.2);
            outline: none;
        }
        
        .submit-button {
            background: linear-gradient(135deg, #4a6cf7 0%, #5e81f4 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            width: 100%;
            font-size: 16px;
            margin-top: 10px;
        }
        
        .submit-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(74, 108, 247, 0.3);
        }
        
        .alert {
            padding: 15px;
            border-radius: var(--border-radius);
            margin-bottom: 20px;
            font-weight: 500;
        }
        
        .alert-success {
            background-color: rgba(40, 167, 69, 0.1);
            border: 1px solid rgba(40, 167, 69, 0.2);
            color: var(--success-color);
        }
        
        .alert-danger {
            background-color: rgba(220, 53, 69, 0.1);
            border: 1px solid rgba(220, 53, 69, 0.2);
            color: var(--danger-color);
        }
        
        .card-animation {
            animation: cardSlideIn 0.5s ease-out;
        }
        
        .password-strength {
            height: 5px;
            margin: 10px 0;
            background: #eee;
            border-radius: 3px;
            overflow: hidden;
            position: relative;
        }
        
        .password-strength-bar {
            height: 100%;
            width: 0;
            background: linear-gradient(to right, #dc3545, #ffc107, #28a745);
            transition: width 0.3s ease;
        }
        
        .password-tips {
            font-size: 12px;
            color: var(--secondary-color);
            margin-top: 5px;
        }
        
        .password-icon {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }
        
        .password-icon-circle {
            width: 80px;
            height: 80px;
            background-color: rgba(74, 108, 247, 0.1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .password-icon-circle i {
            font-size: 40px;
            color: var(--primary-color);
        }
        
        .steps-container {
            margin: 30px 0;
        }
        
        .step {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
        }
        
        .step-number {
            width: 30px;
            height: 30px;
            background-color: var(--primary-color);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }
        
        .step-content {
            flex: 1;
        }
        
        .step-title {
            font-weight: 600;
            margin-bottom: 5px;
            color: var(--dark-color);
        }
        
        .step-description {
            color: var(--secondary-color);
            font-size: 14px;
        }
        
        @keyframes cardSlideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <a href="#" class="sidebar-brand">
            <i class="bi bi-shield-lock"></i> 实验室门禁系统
        </a>
        
        <div class="user-info">
            <div class="user-name">{{ username }}</div>
            <small>欢迎回来</small>
        </div>
        
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="{% url 'back:dashboard' %}">
                    <i class="bi bi-speedometer2 me-2"></i> 控制面板
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{% url 'back:write_card' %}">
                    <i class="bi bi-credit-card me-2"></i> 卡片录入
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="{% url 'back:write_finger' %}">
                    <i class="bi bi-fingerprint me-2"></i> 指纹录入
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="{% url 'back:write_password' %}">
                    <i class="bi bi-key me-2"></i> 密码设置
                </a>
            </li>
            <li class="nav-item mt-5">
                <a class="nav-link" href="{% url 'back:logout' %}">
                    <i class="bi bi-box-arrow-right me-2"></i> 退出登录
                </a>
            </li>
        </ul>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
        <div class="container">
            <div class="card card-animation">
                <div class="header">
                    <h1>录入密码</h1>
                    <a href="{% url 'back:dashboard' %}" class="back-button">返回仪表盘</a>
                </div>
                
                {% if success %}
                <div class="alert alert-success">
                    {{ success }}
                </div>
                {% endif %}
                
                {% if error %}
                <div class="alert alert-danger">
                    {{ error }}
                </div>
                {% endif %}
                
                <div class="password-icon">
                    <div class="password-icon-circle">
                        <i class="fas fa-key"></i>
                    </div>
                </div>
                
                <div class="steps-container">
                    <div class="step">
                        <div class="step-number">1</div>
                        <div class="step-content">
                            <div class="step-title">输入用户ID</div>
                            <div class="step-description">填写需要设置密码的用户ID</div>
                        </div>
                    </div>
                    
                    <div class="step">
                        <div class="step-number">2</div>
                        <div class="step-content">
                            <div class="step-title">设置安全密码</div>
                            <div class="step-description">创建一个强密码，包含字母、数字和特殊字符</div>
                        </div>
                    </div>
                    
                    <div class="step">
                        <div class="step-number">3</div>
                        <div class="step-content">
                            <div class="step-title">确认密码</div>
                            <div class="step-description">再次输入密码以确认无误</div>
                        </div>
                    </div>
                </div>
                
                <form method="post" id="passwordForm">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="user_id">用户ID</label>
                        <input type="text" id="user_id" name="user_id" required placeholder="请输入用户ID">
                    </div>
                    
                    <div class="form-group">
                        <label for="new_password">新密码</label>
                        <input type="password" id="new_password" name="new_password" required placeholder="请输入新密码">
                        <div class="password-strength">
                            <div class="password-strength-bar" id="strengthBar"></div>
                        </div>
                        <div class="password-tips" id="passwordTips">密码强度：请输入密码</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password">确认密码</label>
                        <input type="password" id="confirm_password" name="confirm_password" required placeholder="请再次输入密码">
                    </div>
                    
                    <button type="submit" class="submit-button">提交密码</button>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
    <script>
        const passwordInput = document.getElementById('new_password');
        const confirmInput = document.getElementById('confirm_password');
        const strengthBar = document.getElementById('strengthBar');
        const passwordTips = document.getElementById('passwordTips');
        const form = document.getElementById('passwordForm');
        
        // MQTT客户端配置
        const clientId = "web_client_" + Math.random().toString(16).substr(2, 8);
        const mqttHost = "broker.emqx.io"; // 替换为你的MQTT服务器地址
        const mqttPort = 8083; // WebSocket端口
        let client;
        
        // 连接MQTT服务器
        function connectMQTT() {
            console.log("开始连接MQTT服务器...");
            client = new Paho.MQTT.Client(mqttHost, mqttPort, clientId);
            
            // 设置回调处理器
            client.onConnectionLost = onConnectionLost;
            client.onMessageArrived = onMessageArrived;
            
            // 连接选项
            const options = {
                useSSL: false,
                timeout: 3,
                onSuccess: onConnect,
                onFailure: onFailure,
                userName: "GYJ_LOCK",     // 添加与ESP32相同的用户名
                password: "2140707160"    // 添加与ESP32相同的密码
            };
            
            // 连接到MQTT服务器
            try {
                client.connect(options);
                console.log("MQTT连接请求已发送");
            } catch (e) {
                console.error("MQTT连接错误:", e);
            }
        }
        
        // 连接成功的回调
        function onConnect() {
            console.log("MQTT已连接成功");
            showAlert("success", "MQTT服务器连接成功");
            
            // 订阅密码响应主题
            client.subscribe("/password_response");
            client.subscribe("/password_info");
            console.log("已订阅主题: /password_response, /password_info");
            
            // 获取当前密码
            requestCurrentPassword();
        }
        
        // 连接失败的回调
        function onFailure(e) {
            console.error("MQTT连接失败:", e.errorMessage);
            showAlert("error", "MQTT连接失败: " + e.errorMessage);
        }
        
        // 连接丢失的回调
        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.error("MQTT连接丢失:", responseObject.errorMessage);
                showAlert("error", "MQTT连接丢失: " + responseObject.errorMessage);
                // 尝试重新连接
                setTimeout(connectMQTT, 5000);
            }
        }
        
        // 接收到消息的回调
        function onMessageArrived(message) {
            console.log("收到消息: " + message.destinationName + " - " + message.payloadString);
            
            if (message.destinationName === "/password_response") {
                // 处理密码设置响应
                const response = JSON.parse(message.payloadString);
                if (response.status === "success") {
                    // 显示成功消息
                    showAlert("success", response.message || "密码设置成功！");
                } else {
                    // 显示错误消息
                    showAlert("error", response.message || "密码设置失败，请重试。");
                }
            } else if (message.destinationName === "/password_info") {
                // 处理获取到的当前密码
                const data = JSON.parse(message.payloadString);
                showCurrentPassword(data.password);
            }
        }
        
        // 请求当前密码
        function requestCurrentPassword() {
            if (client && client.isConnected()) {
                // 发送获取密码的请求
                const message = new Paho.MQTT.Message("");
                message.destinationName = "/get_password";
                client.send(message);
            }
        }
        
        // 显示当前密码
        function showCurrentPassword(password) {
            // 创建或更新当前密码显示区域
            let currentPasswordDiv = document.getElementById("currentPassword");
            if (!currentPasswordDiv) {
                currentPasswordDiv = document.createElement("div");
                currentPasswordDiv.id = "currentPassword";
                currentPasswordDiv.className = "alert alert-info mt-3";
                form.parentNode.insertBefore(currentPasswordDiv, form);
            }
            
            currentPasswordDiv.innerHTML = `
                <strong>当前设置的密码:</strong> ${password}
                <div class="mt-2 small text-muted">请注意: 该密码可用于矩阵键盘输入，按"*"开始输入，按"#"结束并确认。</div>
            `;
        }
        
        // 显示提示消息
        function showAlert(type, message) {
            const alertClass = type === "success" ? "alert-success" : "alert-danger";
            const alertDiv = document.createElement("div");
            alertDiv.className = `alert ${alertClass}`;
            alertDiv.innerText = message;
            
            // 插入到表单前面
            form.parentNode.insertBefore(alertDiv, form);
            
            // 5秒后自动消失
            setTimeout(() => {
                alertDiv.remove();
            }, 5000);
        }
        
        // 密码强度检测
        passwordInput.addEventListener('input', function() {
            const password = this.value;
            let strength = 0;
            let tips = '';
            
            if (password.length > 0) {
                // 基本长度检查
                if (password.length >= 8) {
                    strength += 25;
                }
                
                // 包含数字
                if (/\d/.test(password)) {
                    strength += 25;
                }
                
                // 包含小写字母
                if (/[a-z]/.test(password)) {
                    strength += 25;
                }
                
                // 包含大写字母或特殊字符
                if (/[A-Z]/.test(password) || /[^A-Za-z0-9]/.test(password)) {
                    strength += 25;
                }
                
                // 设置提示文本
                if (strength < 25) {
                    tips = '密码强度：非常弱';
                } else if (strength < 50) {
                    tips = '密码强度：弱';
                } else if (strength < 75) {
                    tips = '密码强度：中等';
                } else {
                    tips = '密码强度：强';
                }
            } else {
                tips = '密码强度：请输入密码';
            }
            
            // 更新UI
            strengthBar.style.width = strength + '%';
            passwordTips.textContent = tips;
        });
        
        // 密码确认检查
        confirmInput.addEventListener('input', function() {
            if (this.value && this.value !== passwordInput.value) {
                this.setCustomValidity('两次输入的密码不匹配');
            } else {
                this.setCustomValidity('');
            }
        });
        
        // 表单提交处理
        form.addEventListener('submit', function(e) {
            e.preventDefault(); // 阻止默认表单提交
            console.log("表单提交被触发");
            
            if (passwordInput.value !== confirmInput.value) {
                alert('两次输入的密码不匹配');
                return;
            }
            
            // 构建要发送的数据
            const data = {
                password: passwordInput.value
            };
            
            console.log("准备发送密码:", data);
            
            // 检查是否只包含数字
            if (!/^\d+$/.test(data.password)) {
                showAlert("error", "密码只能包含数字，因为矩阵键盘只能输入数字。");
                return;
            }
            
            // 检查密码长度
            if (data.password.length > 8) {
                showAlert("error", "密码长度不能超过8位数字。");
                return;
            }
            
            // 发送密码到ESP32
            if (client && client.isConnected()) {
                try {
                    const message = new Paho.MQTT.Message(JSON.stringify(data));
                    message.destinationName = "/set_password";
                    client.send(message);
                    console.log("密码已发送: " + JSON.stringify(data));
                    showAlert("success", "密码已发送，等待设备响应...");
                } catch (error) {
                    console.error("发送MQTT消息失败:", error);
                    showAlert("error", "发送失败: " + error.message);
                }
            } else {
                console.error("MQTT未连接");
                showAlert("error", "MQTT未连接，请刷新页面重试。");
                // 尝试重新连接
                connectMQTT();
            }
        });
        
        // 页面加载时连接MQTT
        window.onload = connectMQTT;
    </script>
</body>
</html>